'use strict';

const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const precss = require('precss');
const autoprefixer = require('autoprefixer');
// const Visualizer = require('webpack-visualizer-plugin');
const HappyPack = require('happypack');
const happyThreadPool = HappyPack.ThreadPool({size: 4});

const hotDevServer = 'webpack/hot/dev-server';
// https://github.com/webpack/webpack-dev-server
const webpackHotMiddleware = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true';
const appPath = path.resolve(__dirname, 'public');
const happypackLoader = path.resolve(__dirname, 'node_modules/happypack/loader');
function createHappyPlugin(id, loaders) {
  return new HappyPack({
    id: id,
    loaders: loaders,
    threadPool: happyThreadPool,

    // disable happy caching with HAPPY_CACHE=0
    cache: true,

    // make happy more verbose with HAPPY_VERBOSE=1
    verbose: true,
  });
}

//判断 dll 文件是否已生成
let dllExist = false;
try {
  fs.statSync(path.resolve(appPath, 'dll', 'vendor.dll.js'));
  dllExist = true;
} catch (e) {
  dllExist = false;
}

const webpackConfig = {
  cache: false, //开启缓存,增量编译
  devtool: 'source-map', //生成 source map文件
  stats: {
    colors: true, //打印日志显示颜色
    reasons: true //打印相关模块被引入
  },

  resolve: {
    modules: [
      path.join(__dirname, "client"),
      "node_modules"
    ],
    //模块别名定义，方便直接引用别名
    alias: {
      'react-router-redux': path.resolve(__dirname, 'node_modules/react-router-redux-fixed/lib/index.js'),
    },
    extensions: ['.js', '.jsx', '.json'],
  },

  // 入口文件 让webpack用哪个文件作为项目的入口
  entry: {
    panel: [hotDevServer, webpackHotMiddleware, './client/pages/panel.js']
  },

  // 出口 让webpack把处理完成的文件放在哪里
  output: {
    // 编译输出目录, 不能省略
    path: path.resolve(appPath, 'dist'),
    filename: '[name].bundle.js', //文件名称
    publicPath: '/dist/' //资源路径
  },

  module: {
    rules: [
      // https://github.com/MoOx/eslint-loader
      // {
      //   enforce: 'pre',
      //   test: /\.js$/,
      //   exclude: /node_modules/,
      //   loader: 'eslint-loader'
      // },
      {
        test: /\.jsx?$/,
        // loader: 'babel-loader', // 'babel-loader' is also a legal name to reference
        loader: happypackLoader + "?id=jsx",
        exclude: /node_modules/
      },
      // https://github.com/webpack/url-loader
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)/,
        loader: 'url-loader?limit=10000'
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader?localIdentName=[name]_[local]_[hash:base64:5]!postcss-loader?pack=cleaner'
        // loader: happypackLoader + "?id=css"
      }, {
        test: /\.less$/,
        loader: 'style-loader!css-loader?localIdentName=[name]_[local]_[hash:base64:5]!postcss-loader?pack=cleaner!less-loader'
        // loader: happypackLoader + "?id=less"
      },
      {
        test: /\.(mp4|ogg)$/,
        loader: 'file-loader'
        // loader: happypackLoader + "?id=file"
      }
    ]
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(), // 热部署替换模块
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development')
      }
    }),
    new webpack.LoaderOptionsPlugin({
      debug: true,
      options: {
        // eslint 配置
        eslint: {
          emitError: true, // 验证失败，终止
          configFile: '.eslintrc'
        },
        postcss() {
          return {
            defaults: [
              precss, autoprefixer
            ],
            cleaner: [autoprefixer({
              browsers: ['Android >= 4.0', 'iOS >=8']
            })]
          };
        }
      }
    }),
    createHappyPlugin('jsx', ['babel-loader'])

  ]
};

//创建 HtmlWebpackPlugin 的实例
// https://www.npmjs.com/package/html-webpack-plugin
const entry = webpackConfig.entry;
if (dllExist) {
  webpackConfig.plugins.push(new webpack.DllReferencePlugin({
    context: __dirname,
    /**
     * 在这里引入 manifest 文件
     */
    manifest: require('./public/dll/vendor-manifest.json')
  }));
}

module.exports = webpackConfig;
